package publishsubscribe;

import cn.hutool.core.io.file.FileWriter;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

import java.nio.charset.StandardCharsets;

public class ReceiveLogs02 {

    private static final String EXCHANGE_NAME = "logs";

    public static void main(String[] args) throws Exception{
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.208.134");
        factory.setUsername("admin");
        factory.setPassword("123");

        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.exchangeDeclare(EXCHANGE_NAME, "fanout");
        // 获取随机队列名称(In the Java client, when we supply no parameters to queueDeclare() we create a non-durable, exclusive, autodelete queue with a generated name:)
        // 从以上官方文档的说明可知：采用没有参数的queueDeclare()方法创建的队列，默认是不持久化、排他性、自动删除的队列
        String queueName = channel.queueDeclare().getQueue();
        // 队列和交换机绑定
        channel.queueBind(queueName, EXCHANGE_NAME, "");

        System.out.println(" [*] Write the log to the disk...");

        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
            FileWriter fileWriter = new FileWriter("C:\\Users\\hz21076971\\Desktop\\myJava\\rabbitmq_info_1.txt");
            fileWriter.write(message, true);
            System.out.println(" [x] 数据成功写入文件...");
        };

        channel.basicConsume(queueName, true, deliverCallback, consumerTag -> { });
    }
}
